import React, { useEffect, useState, useMemo } from 'react';
import { Spin, message, Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { useFullscreen } from 'ahooks';
import { connect } from 'umi';

import { FileTextOutlined, FullscreenOutlined, FullscreenExitOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import { TRDefault } from '@/components/index.js';
import questionIcon from '@/assets/helper/question_icon.png';
import questionIconGre from '@/assets/helper/question_icon_gre.svg';
import videoBluePlayIcon from '@/assets/helper/video_blue_icon.png';
import videoPlayIcon from '@/assets/helper/video_play.png';
import videoGrayPlayIcon from '@/assets/helper/video_gray_play.png';
import videoBg from '@/assets/helper/video_bg.png';
import { getParamObj } from '@/utils/index.js';

import { postQueryTabMenuList } from './service';
import { NomalQuestion } from './components';
import { getTabMenuOptions, USER_DATA, handelPreview } from './tool';
import type { IProps, IPublishInfoDataType } from './type';
import { IFileType } from './type';
import styles from './index.less';
import { TjIcon } from '@/tjComponents';

const HelpCenterSecond = (props: IProps) => {
  const { currentUser } = props;
  const [treeSourceData, setTreeSourceData] = useState<DataNode[]>([]);
  const [infoList, setInfoList] = useState<IPublishInfoDataType[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isError, setIsError] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);
  const [preurl, setPreurl] = useState<string>(''); // 文件预览地址
  const [leftNodes, setLeftNodes] = useState<any[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [showFileType, setShowFileType] = useState<IFileType>(IFileType?.VIDEO);
  const [isFullscreen, { enterFullscreen, exitFullscreen }] = useFullscreen(() =>
    document.getElementById('file-container'),
  );

  const showData = infoList?.find((item) => item?.fileType === showFileType);

  const onPlay = async (type: IFileType, file?: any) => {
    const _fileData =
      file ||
      (infoList || [])?.find((item: IPublishInfoDataType) => item?.fileType === type) ||
      infoList[0];
    const _purl = await handelPreview(_fileData, false);
    setPreurl(_purl);
    setShowFileType(type);
  };

  // 初始化获取数据
  const fetchData = async (val?: string) => {
    setIsLoading(true);
    const res: any = await postQueryTabMenuList({ haveInfo: true });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _data = getTabMenuOptions(res?.data || []);
      const obj: any =
        _data?.leftNodes?.find((item: any) => item?.menuCode === val) || _data?.leftNodes[0];
      const _infoList: any[] = obj?.infoList || [];
      const _fileData =
        (_infoList || [])?.find(
          (item: IPublishInfoDataType) => item?.fileType === IFileType.VIDEO,
        ) ||
        (_infoList || [])?.find((item: IPublishInfoDataType) => item?.fileType === IFileType.PDF);
      setTreeSourceData(_data?.modalData || []);
      setShowFileType(_fileData?.fileType);
      setLeftNodes(_data?.leftNodes || []);
      setExpandedKeys(_data?.leftNodes?.map((item: any) => item?.parentKey || item?.key) || []);
      setSelectedKeys([obj?.key]);
      setAutoExpandParent(true);
      setInfoList(_infoList || []);
      if (_fileData) {
        await onPlay(_fileData?.fileType, _fileData);
      }
      setIsError(false);
    } else {
      message.error(res?.message || '查询失败');
      setIsError(true);
    }
    setIsLoading(false);
  };

  const onExpand = (expandedKeysValue: React.Key[]) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onSelect = async (expandedKeysValue: React.Key[]) => {
    let isSelect: any = true;
    treeSourceData.forEach((a) => {
      if (a?.key === expandedKeysValue[0]) {
        if (a && a?.children && a?.children?.length > 0) {
          isSelect = false;
        }
      } else {
        a?.children?.forEach((b) => {
          if (b?.key === expandedKeysValue[0]) {
            if (b && b?.children && b?.children?.length > 0) {
              isSelect = false;
            }
          }
        });
      }
    });
    const obj: any = leftNodes?.find((item: any) => item?.key === expandedKeysValue[0]);
    const _infoList: any[] = obj?.infoList || infoList;
    const _fileData =
      (_infoList || [])?.find((item: IPublishInfoDataType) => item?.fileType === IFileType.VIDEO) ||
      (_infoList || [])?.find((item: IPublishInfoDataType) => item?.fileType === IFileType.PDF);
    setSelectedKeys(isSelect ? expandedKeysValue : selectedKeys);
    setShowFileType(_fileData?.fileType);
    setInfoList(_infoList || []);
    if (_fileData) {
      await onPlay(_fileData?.fileType, _fileData);
    }
  };

  useEffect(() => {
    const _params = getParamObj();
    fetchData(_params?.menuCode);
  }, []);

  // 关闭
  const onClose = () => {
    setVisible(false);
  };

  const treeData = useMemo(() => {
    const loop = (data: DataNode[]): DataNode[] =>
      data.map((item) => {
        const title = (
          <div className={styles.treetitle}>
            <div
              className={
                item?.key === selectedKeys[0] ? styles.treetitleBlueText : styles.treetitleText
              }
            >
              {item?.title}
            </div>
            {!(item?.children?.length > 0) &&
              item?.infoList?.map((info: any) => {
                return (
                  <div className={styles.fileType}>
                    {info?.fileType === IFileType.PDF ? (
                      <FileTextOutlined
                        className={
                          item?.key === selectedKeys[0] ? styles.nameBlueLogo : styles.nameLogo
                        }
                      />
                    ) : (
                      <img
                        className={styles.nameImg}
                        src={item?.key === selectedKeys[0] ? videoBluePlayIcon : videoPlayIcon}
                      />
                    )}
                  </div>
                );
              })}
          </div>
        );
        if (item.children) {
          return { title, key: item.key, children: loop(item.children) };
        }

        return {
          title,
          key: item.key,
        };
      });

    return loop(treeSourceData);
  }, [selectedKeys, treeSourceData]);

  return (
    <div className={styles.container}>
      <div className={styles.main}>
        <div className={styles.header}>
          <div className={styles.title}>帮助中心</div>
          <div
            className={styles.button}
            onClick={() => {
              setVisible(true);
            }}
          >
            <TjIcon dark={questionIcon} gre={questionIconGre} className={styles.logo} />
            <div className={styles.text}>常见问题</div>
          </div>
        </div>
        <div className={styles.bottom}>
          {isLoading ? (
            <Spin className={styles.spin} />
          ) : isError ? (
            <TRDefault type={'error'} message={'系统异常'} />
          ) : treeSourceData?.length > 0 ? (
            <div className={styles.content}>
              <div className={styles.left}>
                <div className={styles.all}>所有教程</div>
                <div className={styles.tree}>
                  <Tree.DirectoryTree
                    onExpand={onExpand}
                    onSelect={onSelect}
                    defaultExpandAll={true}
                    treeData={treeData as any}
                    expandedKeys={expandedKeys}
                    autoExpandParent={autoExpandParent}
                    selectable
                    selectedKeys={selectedKeys}
                    icon={null}
                  />
                </div>
              </div>
              {infoList.length > 0 ? (
                <div className={styles.right}>
                  <div className={styles.menuName}>
                    {showData?.firstMenuName && (
                      <span
                        className={
                          showData?.secondMenuName ? styles.firstMenuName : styles.tabMenuName
                        }
                      >
                        {showData?.firstMenuName}
                        {showData?.secondMenuName && ' / '}
                      </span>
                    )}
                    {showData?.secondMenuName && (
                      <span
                        className={
                          showData?.tabMenuName ? styles.secondMenuName : styles.tabMenuName
                        }
                      >
                        {showData?.secondMenuName}
                        {showData?.tabMenuName && ' / '}
                      </span>
                    )}
                    {showData?.tabMenuName && (
                      <span className={styles.tabMenuName}>{showData?.tabMenuName}</span>
                    )}
                  </div>
                  {infoList.length > 0 && (
                    <div
                      onClick={() =>
                        infoList.length > 1 &&
                        onPlay(showFileType === IFileType.VIDEO ? IFileType.PDF : IFileType.VIDEO)
                      }
                      className={infoList.length > 1 ? styles.showFileType : styles.disShowFileType}
                    >
                      {showFileType === IFileType.PDF ? (
                        infoList.length > 1 ? (
                          <img className={styles.nameImg} src={videoBluePlayIcon} />
                        ) : (
                          <img className={styles.nameImg} src={videoGrayPlayIcon} />
                        )
                      ) : (
                        <FileTextOutlined className={styles.nameLogo} />
                      )}
                      <div className={styles.text}>
                        {showFileType === IFileType.PDF ? '查看视频' : '查看文档'}
                      </div>
                    </div>
                  )}
                  <div className={styles.info}>
                    {showFileType === IFileType.VIDEO && (
                      <div className={styles.video}>
                        <video
                          height={'100%'}
                          width={'100%'}
                          id="video"
                          /*视频地址*/
                          controls /*是否显示播放控件*/
                          poster={videoBg} /*视频封面*/
                          preload="auto" /*预加载*/
                        >
                          <source src={preurl} type="video/mp4" />
                          您的浏览器不支持
                        </video>
                      </div>
                    )}
                    {showFileType === IFileType.PDF && (
                      <div className={styles.preview} id="file-container">
                        <div className={styles.preview_title}>
                          <span>预览</span>
                          {isFullscreen ? (
                            <FullscreenExitOutlined
                              className={styles.preview_icon}
                              onClick={() => exitFullscreen()}
                            />
                          ) : (
                            <FullscreenOutlined
                              className={styles.preview_icon}
                              onClick={() => enterFullscreen()}
                            />
                          )}
                        </div>
                        <div className={styles.preview_file} id="file-container">
                          <div className={styles.file_box}>
                            {USER_DATA.map((item) => (
                              <div key={item}>
                                {currentUser?.name || ''}
                                {currentUser?.mobile || ''}
                              </div>
                            ))}
                          </div>
                          {preurl && (
                            <iframe src={preurl} frameBorder={0} width={'100%'} height={'100%'} />
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              ) : (
                <TRDefault type={'emptysm'} message={'暂无数据'} />
              )}
            </div>
          ) : (
            <TRDefault type={'emptysm'} message={'暂无数据'} />
          )}
        </div>
      </div>
      <NomalQuestion visible={visible} onClose={onClose} />
    </div>
  );
};

export default connect(({ helpCenterSecond, global }: any) => ({
  global,
  menuCode: global.configure.menuCode,
  currentUser: global.configure.currentUser,
  buttonPermissions: global.configure.buttonPermissions,
  helpCenterSecond,
}))(HelpCenterSecond);
